/**
 *@author 易涛
 *@version 1.0
 */
var table = $("#table");
/**
 * 非常重要，控制着管理员账户和其它账户显示，和查询数据的不同，以及操作。
 */
var currentLoginUserType = $("#currentLoginUserType").val();
var sessionId = $("#sessionId").val();

var urlPart="";//default value
Date.prototype.Format = function(fmt)   
{ 
  var o = {   
    "M+" : this.getMonth()+1,                 //月份   
    "d+" : this.getDate(),                    //日
    "h+" : this.getHours(),                   //小时   
    "m+" : this.getMinutes(),                 //分   
    "s+" : this.getSeconds(),                 //秒   
    "q+" : Math.floor((this.getMonth()+3)/3), //季度   
    "S"  : this.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt))   
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));   
  for(var k in o)   
    if(new RegExp("("+ k +")").test(fmt))   
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
  return fmt;   
}; 


inputFileImageInput("drivingLicence1",getRootPath_web() + "/common/file/uploadImage",1);
inputFileInput("drivingLicence",getRootPath_web() + "/common/file/uploadImage",1);

$(function() {
	/**********************根据用户类型隐藏控件 begin*************/
	if(currentLoginUserType!="admin"){//普通用户
		$("#uploadUserArea").hide();
		$("#startTimeArea").hide();
		$("#endTimeArea").hide();
	}
	/**********************根据用户类型隐藏控件 end*************/
	
	//加载datepicker类
	$(".form_datetime").datetimepicker({
		format: 'yyyy-mm-dd',//显示格式
		todayHighlight: 1,//今天高亮
		minView: "month",//设置只显示到月份
		startView:2,
		forceParse: 0,
		showMeridian: 1,
		autoclose: 1//选择后自动关闭
	});
	
	//设置出票table的样式内容
	table.bootstrapTable({
		url: getRootPath_web() + '/common/file/list',
		method : 'post',
		contentType : "application/x-www-form-urlencoded",//必须要有！！！！
		toolbar: '#toolbar', //设置将toolbar集成到bootstrap-table中展示
	  	dataType:'json',
	  	idField : 'Id',// 指定主键列
	  	singleSelect : false,
	  	striped: true,
	  	search : false,
	  	cache : false, // 是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
	  	pagination : true, // 是否显示分页（*）
	  	sortable : false, // 是否启用排序
	  	sortOrder : "asc", // 排序方式
	  	queryParamsType : 'limit',//查询参数组织方式
	  	queryParams : queryParams,// 传递参数（*）
	  	sidePagination : 'server',//指定服务器端分页
	   	pageNumber : 1, // 初始化加载第一页，默认第一页
	  	pageSize : 15, // 每页的记录行数（*）
	  	pageList : [5, 10, 20, 50], // 可供选择的每页的行数（*）
	    showColumns: true,
	    showRefresh: true,
	    columns : [
	  		{
	  			field : 'fileName',
	  			title : '文件名称',
	  			align : 'center'
	  		},{
	  			field : 'createName',
	  			title : '上传者',
	  			align : 'center'
	  		}, {
	  			field : 'createTime',
	  			title : '上传日期',
	  			align : 'center',
	  			formatter: function (value, row, index) {
		 	           if (value == null) {
		 	               return "";
		 	           }
		 	          var offlineTimeStr = new Date(value).Format("yyyy-MM-dd hh:mm:ss");
			           return offlineTimeStr;
		   			}
	  		},{
	  			field : 'detail',
	  			title : '文本描述',
	  			align : 'center'
	  			/*formatter: function (value, row, index) {
	  				var htmlStr="<a class='waves-effect btn btn-danger btn-sm'href='javascript:lookDetail("+index+");'><i class='zmdi'></i>查看文件描述</a>&nbsp;&nbsp;";
			        return offlineTimeStr;
		   		}*/
	  		},{
	  			field : 'status',
	  			title : '管理员是否已读',
	  			align : 'center',
	  			formatter: function (value, row, index) {
	  				
			        if(value==1){
			        	return '<span class="label label-success">是</span>';
			        }else
			        	return '<span class="label label-warning">否</span>';
		   		}
	  		},{
	  			field : 'Id',
	  			title : '操作',
	  			align : 'center',
	  			formatter: function(value, row, index) {
	  				debugger;
	  				var htmlStr =""
	  				if(row.fileType==0){
		  				htmlStr+="<a class='waves-effect btn btn-info btn-sm'href='javascript:showReason(\""+row.id+"\",\""+row.filePath+"\");'><i class='zmdi'></i>下载</a>&nbsp;&nbsp;";
		  				htmlStr+="<a class='waves-effect btn btn-info btn-sm'href='javascript:showBigPicView(\""+row.filePath+"\");'><i class='zmdi'></i>预览</a>&nbsp;&nbsp;";
	  				}else{
	  					htmlStr+="<a class='waves-effect btn btn-warning btn-sm'href='javascript:update("+index+");'><i class='zmdi'></i>修改</a>&nbsp;&nbsp;";
	  					if("admin"==currentLoginUserType)
	  						htmlStr+="<a class='waves-effect btn btn-info btn-sm'href='javascript:read(\""+row.id+"\");'><i class='zmdi'></i>已读</a>&nbsp;&nbsp;";
	  				}
	  				
	  				if("admin"==currentLoginUserType){
	  					htmlStr+="<a class='waves-effect btn btn-danger btn-sm'href='javascript:deleteFile("+index+");'><i class='zmdi'></i>删除</a>&nbsp;&nbsp;";
	  					htmlStr+="<a class='waves-effect btn btn-warning btn-sm'href='javascript:rightFile("+index+");'><i class='zmdi'></i>授权</a>";
	  				
	  				}
	  				return htmlStr;
				},
	  			visible:true
	  		}
		]
	});
	
});

//查看大图  注意：仅支持单个文件查看
function showBigPicView(picUrl){
	if(picUrl == ""){
		$.alert({
			title: '温馨提示',
			content: '暂无附件!',
			autoClose: 'ok|3000',
			buttons: {
				ok: {
					text:"确定"
				}
			}
		});
	}else{
		var insertHtml = "";
		var ext=picUrl.split('.')[1];
	   if(ext=="PNG"||ext=="JPG"||ext=="BMP"||ext=="png"||ext=="jpg"
		   ||ext=="bmp"||ext=="GIF"||ext=="gif"){
	        window.open(getRootPath_web()+"/common/file/showImage?filePath="+picUrl);
	    	/*if(insertHtml == ""){
				insertHtml = '<img id="picDetail" src="'+picUrl+'" >';
			}else{
				insertHtml += '<br><br><img id="picDetail" src="'+picUrl+'" >';
			}
	    	$("#picDetailDialog").modal("show");*/
	    } else{
	    	$.alert({
	    	    title: '',
	    	    content: '只支持图片预览，其他类型文件请下载后查看！',
	    	});
	    	return;
	    }
	}
}


//初始化控件  控件id，和上传路径,只能上传1个文件 1次
function inputFileInput(keyId, uploadUrl, fileNum) {
	 $('#'+keyId+'File').fileinput({
		 language: 'zh', //设置语言
		 enctype: 'multipart/form-data',
	     uploadUrl: getRootPath_web() + "/common/file/uploadImage", //上传的地址
	     allowedFileExtensions : [],//接收的文件后缀
	     showUpload: true, //是否显示上传按钮
	     showPreview: false, //展前预览
	     showCaption: true,//是否显示标题
	     maxFileSize : 100000,//上传文件最大的尺寸
	     minFileCount: 1,
	     maxFileCount : fileNum,//
	     validateInitialCount:true,
	     showUploadedThumbs:false,
	     layoutTemplates:{
	    	 actionUpload:''
	     },
	     dropZoneEnabled: true,//是否显示拖拽区域
	     browseClass: "btn btn-primary",
	     initialPreview: []
     }).on("filebatchselected", function(event, files) {
    	 $("#fileName").val(files[0].name);
    	 $('#'+keyId+'PrewId').val("");
		 $('#'+keyId+'Path').val("");
     }).on('fileuploaderror', function (event, data, previewId, index) {
         var form = data.form, files = data.files, extra = data.extra, response = data.response, reader = data.reader;
     }).on('fileerror', function (event, data) {
         
     }).on('fileuploaded', function (event, data, previewId, index) {
         var resultInfo = data.response;
         if(resultInfo.status == '0'){
        	 //表示上传成功！
        	 var prewId = $('#'+keyId+'PrewId').val();
        	 var path = $('#'+keyId+'Path').val();
        	 if(prewId == ""){
        		 $('#'+keyId+'PrewId').val(previewId);
        		 $('#'+keyId+'Path').val(resultInfo.msg);
        	 }else{
        		 $('#'+keyId+'PrewId').val(prewId+","+previewId);
        		 $('#'+keyId+'Path').val(path+","+resultInfo.msg);
        	 }
         }else{
        	 alert(response.msg);
         }
     }).on('filesuccessremove', function(event, id) {
    	 var prewIds = $('#'+keyId+'PrewId').val().split(",");
    	 var paths = $('#'+keyId+'Path').val().split(",");
    	 var newPrewIds = "";
    	 var newPaths = "";
    	 for(var i=0;i<prewIds.length;i++){
    		 if(prewIds[i] != id){
    			 if(newPaths == ""){
    				 newPrewIds = prewIds[i];
    				 newPaths = paths[i];
    			 }else{
    				 newPrewIds += "," + prewIds[i];
    				 newPaths += "," + paths[i];
    			 }
    		 }
    	 }
    	 $('#'+keyId+'PrewId').val(newPrewIds);
		 $('#'+keyId+'Path').val(newPaths);
     }).on('fileclear', function (event, data, msg) {
    	 $('#'+keyId+'Path').val("");
     }).on('fileimageuploaded', function (event, id) {
    	 alert("加载完成"+id);
     });
}

//图片上传
function inputFileImageInput(keyId, uploadUrl, fileNum) {
	 $('#'+keyId+'File').fileinput({
		 language: 'zh', //设置语言
		 enctype: 'multipart/form-data',
	     uploadUrl: getRootPath_web() + "/common/file/uploadImage", //上传的地址
	     allowedFileExtensions : [],//接收的文件后缀
	     showUpload: true, //是否显示上传按钮
	     showPreview: true, //展前预览
	     showCaption: true,//是否显示标题
	     maxFileSize : 100000,//上传文件最大的尺寸
	     minFileCount: 1,
	     maxFileCount : fileNum,//
	     validateInitialCount:true,
	     showUploadedThumbs:false,
	     layoutTemplates:{
	    	 actionUpload:''
	     },
	     dropZoneEnabled: true,//是否显示拖拽区域
	     browseClass: "btn btn-primary",
	     initialPreview: []
     }).on("filebatchselected", function(event, files) {
    	 $("#fileName1").val(files[0].name);
    	 $('#'+keyId+'PrewId').val("");
		 $('#'+keyId+'Path').val("");
     }).on('fileuploaderror', function (event, data, previewId, index) {
         var form = data.form, files = data.files, extra = data.extra, response = data.response, reader = data.reader;
     }).on('fileerror', function (event, data) {
         
     }).on('fileuploaded', function (event, data, previewId, index) {
         var resultInfo = data.response;
         if(resultInfo.status == '0'){
        	 //表示上传成功！
        	 var prewId = $('#'+keyId+'PrewId').val();
        	 var path = $('#'+keyId+'Path').val();
        	 if(prewId == ""){
        		 $('#'+keyId+'PrewId').val(previewId);
        		 $('#'+keyId+'Path').val(resultInfo.msg);
        	 }else{
        		 $('#'+keyId+'PrewId').val(prewId+","+previewId);
        		 $('#'+keyId+'Path').val(path+","+resultInfo.msg);
        	 }
         }else{
        	 alert(response.msg);
         }
     }).on('filesuccessremove', function(event, id) {
    	 var prewIds = $('#'+keyId+'PrewId').val().split(",");
    	 var paths = $('#'+keyId+'Path').val().split(",");
    	 var newPrewIds = "";
    	 var newPaths = "";
    	 for(var i=0;i<prewIds.length;i++){
    		 if(prewIds[i] != id){
    			 if(newPaths == ""){
    				 newPrewIds = prewIds[i];
    				 newPaths = paths[i];
    			 }else{
    				 newPrewIds += "," + prewIds[i];
    				 newPaths += "," + paths[i];
    			 }
    		 }
    	 }
    	 $('#'+keyId+'PrewId').val(newPrewIds);
		 $('#'+keyId+'Path').val(newPaths);
     }).on('fileclear', function (event, data, msg) {
    	 $('#'+keyId+'Path').val("");
     }).on('fileimageuploaded', function (event, id) {
    	 alert("加载完成"+id);
     });
}

$("#shenPiState").change(function(){
  var value=$(this).val();
  if(value == 0 || value == 2){//表示待审核
  	table.bootstrapTable("showColumn", "Id");
  } else {
		table.bootstrapTable("hideColumn", "Id");
  }
  table.bootstrapTable('refresh');  //刷新
});



//文本上传
function addInfo(){
	$("#keyId").val("");
	$("#fileName").val("");
	$("#drivingLicence").val("");
	$("#drivingLicencePath").val("");
	$('#drivingLicenceFile').fileinput('reset');
	$("#addDriverInfo").modal('show');
}
//图片文件上传
function addInfo1(){
	$("#keyId1").val("");
	$("#fileName1").val("");
	$("#drivingLicence1").val("");
	$("#drivingLicence1Path").val("");
	$('#drivingLicence1File').fileinput('reset');
	$("#addDriverInfo1").modal('show');
}
//修改
function update(index){
	var currentrow = table.bootstrapTable('getData', {useCurrentPage:true})[index];
	$("#rowIndex").val(index);
	$("#addDriverInfo").modal('show');
	$("#drivingLicencePath").val(currentrow.filePath);
	$("#fileName").val(currentrow.fileName);
	$("#keyId").val(currentrow.id);
	$("#detail").val(currentrow.detail);
	$('#drivingLicenceFile').fileinput('reset');
}


function deleteFile(index){
	debugger;

	var currentrow = table.bootstrapTable('getData', {useCurrentPage:true})[index];
	$.confirm({
		type : 'red',
		animationSpeed : 300,
		title : false,
		content : '确定删除该条数据',
		buttons : {
			confirm : {
				text : '确认',
				btnClass : 'waves-effect waves-button',
				action : function() {
					$.post(getRootPath_web()+'/common/file/deleteFile', currentrow, function(data) {
						$.alert("删除成功");
						$("#table").bootstrapTable('refresh');  //刷新
					});}
			},
			cancel : {
				text : '取消',
				btnClass : 'waves-effect waves-button'
			}
		}
	});
}


$("#cancelDialog").click(function (){
	$("#rightFile").modal('hide');
});

function rightFile(index){
	debugger;
	var currentrow = table.bootstrapTable('getData', {useCurrentPage:true})[index];

	var formData ={
		"createId":	currentrow.createId,
		"fileId":currentrow.id
	};
	$("#fileId").val(currentrow.id);
	//授权查询文件创建者；如果是会员为两个人；如果是账号 一个人
	$("#rightFile").modal('show');
	$.ajax({
	    url:getRootPath_web()+"/common/file/queryRightUsers",
	    type:"post",
	    data:formData,
	    dataType:"json",
	    success:function(data){
	    	//显示可授权用户
	    	var checkUserIds ="@@"
	    	for(var j=0;j<data.res.checkedUsers.length;j++){
	    		checkUserIds+=data.res.checkedUsers[j].userId
			}
	    	debugger;
	    	$('#rightFileGroup').html("");
	    	for(var i=0;i<data.res.listRightUsers.length;i++){
	    		if(data.res.listRightUsers[i].USER_TYPE=="general") {
	    			var checked =""
	    			if(checkUserIds.indexOf(data.res.listRightUsers[i].USER_ID)>-1)
	    				 checked ="checked =checked"
	    			//会员
	    			$("#rightFileGroup").append('<span id="memberName">'+data.res.listRightUsers[i].USER_NAME+'</span> &nbsp; &nbsp;<input type="checkbox" id="memberId" '+checked+'   value="'+data.res.listRightUsers[i].USER_ID+'"><br/>');
	    		}else{
	    			var checked =""
		    			if(checkUserIds.indexOf(data.res.listRightUsers[i].USER_ID)>-1)
		    				 checked ="checked =checked"
	    			$("#rightFileGroup").append('<span id="userName">'+data.res.listRightUsers[i].USER_NAME+'</span> &nbsp; &nbsp;<input type="checkbox" id="userId" '+checked+'   value="'+data.res.listRightUsers[i].USER_ID+'"><br/>');
	    		}
	    	}
	    },
	    error:function(){
	     
	    }
	  });
}

//保存授权

$("#rightBtn").click(function (){
	debugger;
	var fileId =$("#fileId").val();
	var userCheck =$('#userId').is(':checked');
	var memberCheck =$('#memberId').is(':checked');
	var userId =$('#userId').val();
	var memberId =$('#memberId').val();
	var formData={
			"fileId":fileId,
			"userCheck":userCheck,
			"memberCheck":memberCheck,
			"userId":userId,
			"memberId":memberId
	}
	$("#rightFile").modal('hide');
	$.ajax({
	    url:getRootPath_web()+"/common/file/updateRightUsers",
	    type:"post",
	    data:formData,
	    dataType:"json",
	    success:function(data){
	    	//显示可授权用户
	    	debugger;
	    	$.alert({
				title: '授权',
				content: '授权成功',
				autoClose: 'ok|3000',
				buttons: {
					ok: {
						text:"确定"
					}
				}
			});
	    },
	    error:function(){
	     
	    }
	  });
	
});



//下载
function showReason(id,filePath) {
	console.log(filePath);
	if(filePath==""){
		$.alert({
			title: '温馨提示',
			content: '暂无附件!',
			autoClose: 'ok|3000',
			buttons: {
				ok: {
					text:"确定"
				}
			}
		});
	}else{
		var formData={
				"status":"1",
				"id":id,
		}
		
		$.ajax({
		    url:getRootPath_web()+"/common/file/insertFile",
		    type:"post",
		    data:formData,
		    dataType:"json",
		    success:function(data){

				table.bootstrapTable('refresh');  //刷新
		    },
		    error:function(){
		     
		    }
		  });
		window.location.href= getRootPath_web()+"/common/file/dowland?filePath="+filePath;
	}
}

//已读
function read(id){
	debugger;
	var formData={
			"status":"1",
			"id":id,
	}
	$.ajax({
	    url:getRootPath_web()+"/common/file/insertFile",
	    type:"post",
	    data:formData,
	    dataType:"json",
	    success:function(data){

	    	table.bootstrapTable('refresh');  //刷新
	    },
	    error:function(){
	     
	    }
	  });

}

//查询方法
$('#search').click(function(){
	var opt = {
      url: getRootPath_web()+"/common/file/list",
      silent: true,
      query:{}//queryParams中已经订好了，无需再次传递；
	};
	//显示对话框模型
	$("#addDialog").modal('show');
	table.bootstrapTable('refresh', opt);
});

$("#reset").click(function(){
	$("#createName").val("");
	$("#fileNameSearch").val("");
	$("#detailSearch").val("");
	$("#startTime").val("");
	$("#endTime").val("");
	table.bootstrapTable('refresh');  //刷新
});

//table加载成功时触发
table.on('load-success.bs.table',function(data){
	$("#addDialog").modal('hide');
});


//请求服务数据时所传参数
function queryParams(params) {
	var createName =$("#createName").val();
	var fileName =$("#fileNameSearch").val();
	var detail =$("#detailSearch").val();
	var startTime =$("#startTime").val();
	var endTime =$("#endTime").val();
	
	var formData={
			"limit" : params.limit,
			"offset" : params.offset,
			"createName":createName,
			"fileName":fileName,
			"detail":detail,
			"startTime":startTime,
			"endTime":endTime,
			"currentLoginUserType":currentLoginUserType,
			"sessionId":sessionId
	}
	return formData;
}

//重置
$('#resetDialog').click(function() {
	$("#drivingLicence").val("");
	$("#drivingLicencePath").val("");
	$("#fileName").val("");
	$("#detail").val("");
});
$('#resetDialog1').click(function() {
	$("#drivingLicence1").val("");
	$("#drivingLicence1Path").val("");
	$("#fileName1").val("");
	$("#detail1").val("");
});
//提交数据
$('#submitBtn').click(function() {
	var drivingLicence = $("#drivingLicence").val();
	var drivingLicencePath = $("#drivingLicencePath").val();
	var fileName = $("#fileName").val();
	//文本描述
	var detail = $("#detail").val();
	if(drivingLicencePath == "" && detail=="") {
		alert("请上传一个文件或填写文字描述！");
		return;
	}
	
	var formData={
			"imgFlag":"1",
			"status":"0",
			"id":$("#keyId").val(),
			"filePath":drivingLicencePath,
			"detail":detail,
			"fileName":fileName
	}
	
	$.ajax({
	    url:getRootPath_web()+"/common/file/insertFile",
	    type:"post",
	    data:formData,
	    dataType:"json",
	    success:function(data){
	    	$("#addDriverInfo").modal('hide');
	    	if(data.status == "0"){
	    		$.alert({
	    		    title: '温馨提示',
	    		    content: data.msg,
	    		    autoClose: 'ok|3000',
	    		    buttons: {
	    		    	ok: {
	    		    		text:"确定"
	    		    	}
	    		    }
	    		});
	  			table.bootstrapTable('refresh');  //刷新
	    	}
	    },
	    error:function(){
	     
	    }
	  });
	
});

//提交文件图片数据
$('#submitBtn1').click(function() {
	var drivingLicence = $("#drivingLicence1").val();
	var drivingLicencePath = $("#drivingLicence1Path").val();
	var fileName = $("#fileName1").val();
	//文本描述
	var detail = $("#detail1").val();
	if(drivingLicencePath == "" && detail=="") {
		alert("请上传一个文件或填写文字描述！");
		return;
	}
	
	var formData={
			
			"imgFlag":"0",
			"status":"0",
			"id":$("#keyId1").val(),
			"filePath":drivingLicencePath,
			"detail":detail,
			"fileName":fileName
	}
	
	$.ajax({
	    url:getRootPath_web()+"/common/file/insertFile",
	    type:"post",
	    data:formData,
	    dataType:"json",
	    success:function(data){
	    	$("#addDriverInfo1").modal('hide');
	    	if(data.status == "0"){
	    		$.alert({
	    		    title: '温馨提示',
	    		    content: data.msg,
	    		    autoClose: 'ok|3000',
	    		    buttons: {
	    		    	ok: {
	    		    		text:"确定"
	    		    	}
	    		    }
	    		});
	  			table.bootstrapTable('refresh');  //刷新
	    	}
	    },
	    error:function(){
	     
	    }
	  });
	
});
//查看文件描述
function lookDetail(index){
	
}
function getRootPath_web() {
    //获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
    var curWwwPath = window.document.location.href;
    //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    //获取主机地址，如： http://localhost:8083
    var localhostPaht = curWwwPath.substring(0, pos);
    //获取带"/"的项目名，如：/uimcardprj
    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
    return "http://103.197.70.25/FirstCooperate";
}
